/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package snake.core.listeners;

import java.awt.Container;
import snake.SnakeGame;
import snake.core.PositionToComponentNoConverter;
import snake.core.gameinterface.MainWindow;
import snake.gameplay.Position;
import snake.gameplay.Snake;

/**
 *
 * @author Fein
 */
abstract class BaseSnakeListener {

    static Snake snake = null;
    Container container = null;

    public BaseSnakeListener() {
    }

    public BaseSnakeListener(Snake snake, Container container) {
        this.snake = snake;
        this.container = container;
    }
    
    public void makeViewChange(Position newSnakeHeadPosition){
         container.getComponent(PositionToComponentNoConverter.convert(snake.getHeadPosition())).setBackground(MainWindow.FIELD_COLOR);
         container.getComponent(PositionToComponentNoConverter.convert(newSnakeHeadPosition)).setBackground(MainWindow.SNAKE_COLOR);
         
         
    }

    public void changePosition(Position changePosition) {
        Position newSnakeHeadPosition = Position.sumPositions(snake.getHeadPosition(), changePosition);

        boolean checkField = checkFieldOutOfBound(newSnakeHeadPosition);
        boolean checkTail = checkTailTouch();


        if (checkField && checkTail) {
           makeViewChange(newSnakeHeadPosition);
           snake.setHeadPosition(newSnakeHeadPosition);
        } else {
            gameOver();
        }
    }

    public void changePosition(int coordinateX, int coordinateY) {
        changePosition(new Position(coordinateX, coordinateY));
    }

    public void gameOver() {
        container.setVisible(false);
    }

    private boolean checkFieldOutOfBound(Position newSnakePosition) {
        if (newSnakePosition.getCoordinateX() < 0 || newSnakePosition.getCoordinateY() < 0) {
            return false;
        }
        if (newSnakePosition.getCoordinateX() >= SnakeGame.SIZEX || newSnakePosition.getCoordinateY() >= SnakeGame.SIZEY) {
            return false;
        }
        return true;
    }

    private boolean checkTailTouch() {
        return true;
    }
}
